﻿using System;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace StarHelper
{

    public static class EmailHelper
    {
        /// <summary>
        /// 正则验证Email格式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static bool IsEmailAddress(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return false;
            }
            string emailregex = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";
            var regex = new Regex(emailregex);
            return regex.IsMatch(value);
        }
        #region 发邮件
        /// <summary>
        /// 发邮件
        /// </summary>
        /// <param name="email">邮件接收人</param>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        /// <param name="fromaddress">发件人地址</param>
        /// <param name="displayName">发件人显示名称</param>
        /// <param name="fromaddresspwd">发件人密码</param>
        /// <param name="smtphost">SMTP服务器 默认 QQ邮箱 smtp.exmail.qq.com</param>
        /// <param name="port">SMTP端口 默认 587</param>
        /// <param name="emails">同时接收人</param>
        /// <param name="attachs">附件</param>
        /// <param name="csemails">抄送人</param>
        /// <returns></returns>
        public static bool SendEmail(string email, string subject, string body, string fromaddress = "", string displayName = "", string fromaddresspwd = "", string smtphost = "smtp.exmail.qq.com", int port = 587, string emails = "", string attachs = "", string csemails = "")
        {
            try
            {
                var mailFrom = new MailAddress(fromaddress, displayName);
                var mailTo = new MailAddress(email);
                MailMessage mailmessage = new MailMessage(mailFrom, mailTo);
                mailmessage.Priority = MailPriority.Normal; //邮件优先级
                mailmessage.Subject = subject;
                mailmessage.Body = body;
                mailmessage.IsBodyHtml = true;
                SmtpClient smtpClient = new SmtpClient(smtphost, port);//smtp地址以及端口号
                smtpClient.Credentials = new NetworkCredential(fromaddress, fromaddresspwd);//smtp用户名密码
                smtpClient.EnableSsl = true; //启用ssl

                var emailList = emails.Split(';', '；', '，', ',').Where(w => !string.IsNullOrWhiteSpace(w) && IsEmailAddress(w)).ToList();
                if (emailList.Count > 0)
                {
                    foreach (var item in emailList)
                    {
                        mailmessage.To.Add(item);
                    }
                }


                if (!string.IsNullOrWhiteSpace(csemails))
                { //抄送
                    var listcs = csemails.Split(';', '；', '，', ',').Where(w => !string.IsNullOrWhiteSpace(w) && IsEmailAddress(w)).ToList();
                    if (listcs.Count > 0)
                    {
                        foreach (var csemail in listcs)
                        {
                            MailAddress cc = new MailAddress(csemail);//获取输入的抄送人邮箱地址
                            mailmessage.CC.Add(cc);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(attachs) && System.IO.File.Exists(attachs))
                {//附件
                    Attachment attach = new Attachment(attachs);
                    mailmessage.Attachments.Add(attach);
                }
                try
                {
                    smtpClient.Send(mailmessage); //发送邮件
                    return true;
                }
                catch
                {
                    smtpClient.Port = 465;
                    try
                    {
                        smtpClient.Send(mailmessage); //发送邮件
                        return true;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (SmtpException se) //smtp错误
            {
                throw se;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


        #region 发邮件【异步】
        /// <summary>
        /// 发邮件【异步】
        /// </summary>
        /// <param name="email">邮件接收人</param>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        /// <param name="fromaddress">发件人地址</param>
        /// <param name="displayName">发件人显示名称</param>
        /// <param name="fromaddresspwd">发件人密码</param>
        /// <param name="smtphost">SMTP服务器</param>
        /// <param name="port">SMTP端口</param>
        /// <param name="emails">同时接收人</param>
        /// <param name="attachs">附件</param>
        /// <param name="csemails">抄送人</param>
        /// <returns></returns>
        public static async Task SendEmailAsync(string email, string subject, string body, string fromaddress = "", string displayName = "", string fromaddresspwd = "", string smtphost = "smtp.exmail.qq.com", int port = 587, string emails = "", string attachs = "", string csemails = "")
        {
            try
            {
                var mailFrom = new MailAddress(fromaddress, displayName);
                var mailTo = new MailAddress(email);
                MailMessage mailmessage = new MailMessage(mailFrom, mailTo);
                mailmessage.Priority = MailPriority.Normal; //邮件优先级
                mailmessage.Subject = subject;
                mailmessage.Body = body;
                mailmessage.IsBodyHtml = true;
                SmtpClient smtpClient = new SmtpClient(smtphost, port);//smtp地址以及端口号
                smtpClient.Credentials = new NetworkCredential(fromaddress, fromaddresspwd);//smtp用户名密码
                smtpClient.EnableSsl = true; //启用ssl

                var emailList = emails.Split(';', '；', '，', ',').Where(w => !string.IsNullOrWhiteSpace(w) && IsEmailAddress(w)).ToList();
                if (emailList.Count > 0)
                {
                    foreach (var item in emailList)
                    {
                        mailmessage.To.Add(item);
                    }
                }


                if (!string.IsNullOrWhiteSpace(csemails))
                { //抄送
                    var listcs = csemails.Split(';', '；', '，', ',').Where(w => !string.IsNullOrWhiteSpace(w) && IsEmailAddress(w)).ToList();
                    if (listcs.Count > 0)
                    {
                        foreach (var csemail in listcs)
                        {
                            MailAddress cc = new MailAddress(csemail);//获取输入的抄送人邮箱地址
                            mailmessage.CC.Add(cc);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(attachs) && System.IO.File.Exists(attachs))
                {//附件
                    Attachment attach = new Attachment(attachs);
                    mailmessage.Attachments.Add(attach);
                }
                try
                {
                    await smtpClient.SendMailAsync(mailmessage); //发送邮件
                }
                catch
                {
                    smtpClient.Port = 465;
                    try
                    {
                        await smtpClient.SendMailAsync(mailmessage); //发送邮件
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (SmtpException se) //smtp错误
            {
                throw se;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

    }
}
